import path from 'path'
import { NodeSSH } from 'node-ssh'
import { exec, execSync } from 'child_process'
import inquirer from 'inquirer'
const fileName = "dist.zip"
const localSrc = path.resolve('dist/' + fileName)
import fs from 'fs'


const remoteSrc = '/www/wwwroot/game.xtiger.cn/'
const sshConnect = (
    src: string,
    des: string,
    options: { callback?: Function; directory?: boolean }
) => {
    const ssh = new NodeSSH()
    
    ssh
        .connect({
            host: '42.193.231.115',
            port: 22,
            username: 'root',
            privateKey: fs.readFileSync('C:\\Users\\Administrator\\.ssh\\id_rsa').toString()
        })
        .then(async () => {

            const methods = options?.directory ? 'putDirectory' : 'putFile'
            await ssh[methods](src, des + fileName)
            console.log('文件上传成功')
            await ssh.execCommand(`cd ${des}; unzip -o ${fileName}`);
            console.log("文件解压完毕");
            options?.callback?.()
            ssh.dispose()
        })
        .catch((e: Error) => {
            console.log('ssh连接失败：', e)
        })
}
(async function () {
    const store = execSync("git config --get credential.helper")
    if (store.toString() != "store") {
        execSync("git config credential.helper store")
    }

    // @ts-ignore
    const { commit } = await inquirer.prompt({ name: "commit", type: "input", message: "请输入提交信息" })
    exec(`git add . && git commit -m "${commit}" && git push`).stdout?.on("data", (data) => {
        console.log(`stdout: ${data}`);
        sshConnect(localSrc, remoteSrc, { directory: false })
    }).on("error", (err) => {
        return console.error(err);
    }).on("end", () => {
        console.log("提交成功");
    })

})()


